<?php
/**
Plugin Name: WP Artician Widgets
Plugin URI: http://wp-artician.googlecode.com
Description: Artican Portfolio gallery widgets
Author: Avice De&apos;v&eacute;reux
Version: 1.0
Author URI: http://blog.kaizeku.com/
*/

/**
 * @package	WordPress
 * @subpackage	wp-artician-widget
 * 
 * @category	widget
 * @author	Avice (ChaosKaizer) De'vereux <ck+wp-articiane@kaizeku.com>
 * @copyright 	2009 Avice De'vereux
 * @license 	http://www.gnu.org/licenses/old-licenses/gpl-2.0.html GNU General Public License v2
 * @version 	CVS: $Id: wp-artician.php 4 2009-06-03 04:51:59Z chaoskaizer $
 * @since 	1.0
 */



/**
 * widget version
 */
define('WPA_VERSION', (float) 1.0);


/**
 * text domain name
 */
define('WPA_META','wp-artician');


/**
 * simplePie cache duration
 */
define('WPA_CACHE_DURATION',43200);


/**
 * artician's portfolio feed uri
 */
define('WPA_ARTICIAN_PORTFOLIO_RSS_URI','http://%s.artician.com/rss/portfolio/');


/**
 * @var string User agent string 
 * 
 */
define('WPA_UA_FF','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 GTB5');


/**
 * default useragent
 */
define('WPA_UA', 'WordPress/' . $wp_version . '; ' . get_bloginfo( 'url' ).' wp-artician/'.WPA_VERSION );


/**
 * register plugin text domain 
 */
add_action('init', 'WParticianWidget_textdomain');


/**
 *  register default widget stylesheets
 */
wp_register_style(WPA_META,WP_PLUGIN_URL.'/'.WPA_META.'/'.WPA_META.'.css',array(),'1.0');


/**
 * 
 */
function WParticianWidget_textdomain() {
	load_plugin_textdomain(WPA_META, false, WPA_META);
}


/**
 * public wpa_fetch_feed()
 */
function wpa_fetch_feed($instance){
	
	$name = (string) ((isset($instance['username']) && !empty($instance['username']) ) ? $instance['username'] : '' );;
	$limit = (int) ((isset($instance['limit']) && !empty($instance['limit']) ) ? $instance['limit'] : 5 );
	$sortby = ((isset($instance['sortby']) && !empty($instance['sortby']) ) ? $instance['sortby'] : 'latest' );
	$feedburner_url = ((isset($instance['feedburner_url']) && !empty($instance['feedburner_url']) ) ? $instance['feedburner_url'] : false );
	$thumb_size = ((isset($instance['thumb_size']) && !empty($instance['thumb_size']) ) ? $instance['thumb_size'] : '75' );	
	
	$url = ($feedburner_url) ? $feedburner_url : sprintf(WPA_ARTICIAN_PORTFOLIO_RSS_URI, $name);	
	
	if (!class_exists('SimplePie')){	
		$file = ABSPATH . WPINC . DIRECTORY_SEPARATOR.'class-feed.php';	
		
		if(!file_exists($file))	return false;		
		
		include_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR.'class-feed.php');	
	}
		
	$feed = new SimplePie();	
	$feed->set_feed_url($url);
	//$feed->force_fsockopen(true);
	$feed->set_cache_class('WP_Feed_Cache');
	//$feed->set_file_class('WP_SimplePie_File');
	$feed->set_cache_duration(WPA_CACHE_DURATION);	 
	$feed->set_useragent(WPA_UA);	
	$feed->init();
	$feed->handle_content_type();
	
	if ($feed){
		$items = $feed->get_items();

		if (isset($instance['sortby'])){
			
			switch ($sortby){
				case 'oldest':
					$items = array_reverse($items);	
				break;	
				case 'random':
					srand((float) microtime() * 1000000);
					shuffle($items);				
				break;
			}
		}	
		//$feed_limit = $feed->get_item_quantity($limit);		
		echo '<ol class="thumb-'.$thumb_size.'">'.PHP_EOL;
		$n = 1;
		foreach($items as $item){
			if ($n<=$limit){
				
			$thumbs = $item->get_item_tags('http://search.yahoo.com/mrss/', 'thumbnail');			
			$thumb_url = false;
			
			$credits = $item->get_item_tags('http://search.yahoo.com/mrss/', 'credit');
			$credit = sprintf(__('by %s',WPA_META),$credits[0]['data']);
			
			$portfolio_uri = $item->get_link();
			
			if (isset($instance['feedburner_url'])){
				$portfolio_uri = $item->get_item_tags('http://rssnamespace.org/feedburner/ext/1.0','origLink');		
				$portfolio_uri = $portfolio_uri[0]['data'];	
			}
					
			echo '<li><a href="'.$portfolio_uri.'" title="'.esc_attr($item->get_title()).'">';
			
			foreach($thumbs as $thumb){
				if ($thumb['attribs']['']['width'] == $thumb_size){
					$thumb_url = $thumb['attribs']['']['url'];				
				}																
			}
			
		 	if ($thumb_url){	 										 			 			
				echo '<img src="'.$thumb_url.'" height="'.$thumb_size.'" width="'.$thumb_size.'" alt="'.esc_attr($item->get_title()).' '.$credit.'" title="'.esc_attr($item->get_title()).'" />';
			}
			
			if (isset($instance['caption']) && $instance['caption'] == 1){
				echo '<small>'.$item->get_title().'</small>';	
			}
			
			echo '</a>';
			
			echo '</li>'.PHP_EOL;
			$n++;
			}	
		}		
		
		echo '</ol>'.PHP_EOL;
		
		if (isset($instance['feed_link']) && $instance['feed_link']){
			echo '<p class="wpa_feed_link"><a href="'.$url.'" style="background-image:url(\''.includes_url('images/rss.png').'\')" rel="external nofollow" title="Subscribe to this feed">Subscribe to this feed</a></p>';
		}
		
		unset($items,$feed);
	} 				
}


/**
 * WParticianWidget Class
 * multiple widget
 */
class WParticianWidget extends WP_Widget 
{	
	function WParticianWidget() {		
		$options = array('classname' => 'widget_wpa_portfolio', 'description' => 'Artician portfolio feeds gallery' );
        $this->WP_Widget('wpa',__('Artician Portfolio'),$options);	
    }

    function widget($args, $instance) {		
        extract( $args );
        
        $title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Artician Portfolio',WPA_META ) : $instance['title']);
        ?>
              <?php echo $before_widget; ?>
                  <?php echo $before_title. $title. $after_title; ?>
               <div id="wpa-widget">
			   <?php wpa_fetch_feed($instance);?>			   
			   </div>   
              <?php echo $after_widget; ?>
        <?php
    }

    function update($new_instance, $old_instance) {	
    	
		$instance = $old_instance;
		$instance['title'] = strip_tags($new_instance['title']);
		$instance['username'] = strip_tags($new_instance['username']);
 		$instance['limit'] = strip_tags($new_instance['limit']);
 		
		if ( in_array( $new_instance['sortby'], array( 'latest', 'oldest','random' ) ) ) {
			$instance['sortby'] = $new_instance['sortby'];
		} else {
			$instance['sortby'] = 'latest';
		}
		
 		$instance['feedburner_url'] = strip_tags($new_instance['feedburner_url']);
 		
		if ( in_array( $new_instance['thumb_size'], array( '75', '150' ) ) ) {
			$instance['thumb_size'] = $new_instance['thumb_size'];
		} else {
			$instance['thumb_size'] = '75';
		}

		$checkbox = array( 'feed_link' => 0, 'caption' => 0);
		foreach ( $checkbox as $field => $val ) {
			if ( isset($new_instance[$field]) ){
				$instance[$field] = 1;
			} else {
        $instance[$field] = 0;
			}	
		}		
 		
		return $instance;
    }
    
    
	/**
	 * Widget form controller
	 */
    function form($instance) {	
    	$deb = $instance;
    	$default_options = array('title' =>__('Artician Portfolio',WPA_META),'username' => '', 'limit' => 5,
		'thumb_size'=>'75','sortby'=>'latest');
    	$instance = wp_parse_args( (array) $instance, $default_options );
		// the form
        ?>
            <p>
            	<?php self::_html_input($instance,'title',__('Title:',WPA_META)); ?>			
			</p>
            <p>
            	<?php self::_html_input($instance,'username',__('Artician subdomain name:',WPA_META)); ?>			
				<br /><small>subdomain = http://ck.artician.com subdomain name = ck </small>
			</p>
            <p>
            	<?php self::_html_input($instance,'limit',__('Limit:',WPA_META)); ?>			
			</p>
			<p>
				<label for="<?php echo $this->get_field_id('thumb_size'); ?>"><?php _e( 'Thumbnail size:', WPA_META ); ?></label>
				<select name="<?php echo $this->get_field_name('thumb_size'); ?>" id="<?php echo $this->get_field_id('thumb_size'); ?>" class="widefat" size="2"  style="height:44px">
					<option value="75"<?php selected( $instance['thumb_size'], '75' ); ?>><?php _e('75 px'); ?></option>
					<option value="150"<?php selected( $instance['thumb_size'], '150' ); ?>><?php _e('150 px'); ?></option>
				</select>
			</p>				
			<p>
				<label for="<?php echo $this->get_field_id('sortby'); ?>"><?php _e( 'Sort by:', WPA_META ); ?></label>
				<select name="<?php echo $this->get_field_name('sortby'); ?>" id="<?php echo $this->get_field_id('sortby'); ?>" class="widefat" size="3"  style="height:64px">
					<option value="latest"<?php selected( $instance['sortby'], 'title' ); ?>><?php _e('Latest first'); ?></option>
					<option value="oldest"<?php selected( $instance['sortby'], 'oldest' ); ?>><?php _e('Oldest first'); ?></option>
					<option value="random"<?php selected( $instance['sortby'], 'random' ); ?>><?php _e( 'Random' ); ?></option>
				</select>
			</p>	
			<div id="wpa-moreoptions">		
            <p>
            	<?php self::_html_input($instance,'feedburner_url',__('Feedburner URL:',WPA_META)); ?>
				<br /><small>Proxy artician feed via Google feedburner. i.e http://feeds2.feedburner.com/artician-portfolio?format=xml</small>			
			</p>
			<hr style="border-color:#eee"/>	
			<p>
			<input class="checkbox" type="checkbox" <?php checked($instance['feed_link'], true) ?> id="<?php echo $this->get_field_id('feed_link'); ?>" name="<?php echo $this->get_field_name('feed_link'); ?>" />
			<label for="<?php echo $this->get_field_id('feed_link'); ?>"><?php _e('Show feed link'); ?></label>
			</p>		
			<p>
			<input class="checkbox" type="checkbox" <?php checked($instance['caption'], true) ?> id="<?php echo $this->get_field_id('caption'); ?>" name="<?php echo $this->get_field_name('caption'); ?>" />
			<label for="<?php echo $this->get_field_id('caption'); ?>"><?php _e('Show caption',WPA_META); ?></label>
			</p>
			</div>								
        <?php 
    }
    
	function _html_input($instance,$name,$label='label',$type='text',$classname="widefat"){
		
		echo '<label for="'.$this->get_field_id($name).'">'.$label.'</label>';
		echo '<input class="'.$classname.'" id="'.$this->get_field_id($name).'" name="'.$this->get_field_name($name).'" type="'.$type.'" value="'.esc_attr($instance[$name]).'" />';
	}    

}

add_action('widgets_init', create_function('', 'return register_widget("WParticianWidget");'));

if (is_active_widget('WParticianWidget',false,'wpa')){
	wp_enqueue_style(WPA_META);
}

/* [EOL] */	